package com.hornsun.jwt;

import com.google.common.base.Throwables;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;

/**
 * @author 编译中、、
 * @date 2017/12/24
 */
public class RawAccessJwtToken implements JwtToken {
    private static final Logger logger = LoggerFactory.getLogger(RawAccessJwtToken.class);
    private String token;

    public RawAccessJwtToken(String token) {
        this.token = token;
    }

    /**
     * Parses and validates JWT Token signature.
     *
     * @throws BadCredentialsException
     * @throws JwtExpiredTokenException
     */
    public Jws<Claims> parseClaims(String signingKey) {

        try {
            return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
        } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
            logger.error("Invalid JWT Token, {}", Throwables.getStackTraceAsString(ex));
            throw new JwtTokenInvalidException("Invalid JWT token: ");
        } catch (ExpiredJwtException expiredEx) {
            logger.error("JWT Token is expired");
            throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
        }

    }

    @Override
    public String getToken() {
        return token;
    }
}
